package com.xtravel.common.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.xtravel.R;
import com.xtravel.common.fragment.BaseFragment;
import com.xtravel.common.fragment.FragmentFactory;


public class HomeActivity extends FragmentActivity {
    private FragmentManager fragmentManager;
    private RadioGroup radioGroup;
    private int lastCheckedFragmentId;
    private int lastCheckedRadioId;

    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        setContentView(R.layout.home_main_page);


        fragmentManager = getSupportFragmentManager();
        radioGroup = (RadioGroup) findViewById(R.id.main_radio_graoup);
        radioGroup.setOnClickListener(null);
        ((RadioButton) findViewById(R.id.main_rb_tweet)).setChecked(true);
        startFragment(R.id.main_rb_tweet);
        lastCheckedRadioId = 0;
    }

    public void onRadioClick(View view) {
        int checkedId = view.getId();
        startFragment(checkedId);
        reclickFragment(checkedId);

    }


    private void reclickFragment(int checkedId) {
        if (lastCheckedRadioId == checkedId) {
            BaseFragment fragment = FragmentFactory.getInstanse(checkedId);
            fragment.onReClick();
        } else {
            lastCheckedRadioId = checkedId;
        }
    }

    private void startFragment(int checkedId) {
        BaseFragment fragment = FragmentFactory.getInstanse(checkedId);
        if (lastCheckedFragmentId == checkedId) {
            fragment.onFragmentChange(false);
            return;
        }

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.content, fragment);
        transaction.commit();
        fragment.onFragmentChange(true);
        lastCheckedFragmentId = checkedId;
    }
}
